package com.vivo.tasks;


import com.dingtalk.api.response.OapiWorkrecordAddResponse;
import com.dingtalk.api.response.OapiWorkrecordUpdateResponse;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.vivo.Utils.DingConfUtil;
import com.vivo.Utils.SendDingDingMsgUtil;
import com.vivo.dingtalk.entity.DingUserInfo;
import com.vivo.dingtalk.entity.DingWorkRecord;
import com.vivo.dingtalk.service.DingUserInfoService;
import com.vivo.dingtalk.service.DingWorkRecordService;
import com.vivo.dingtalk.web.vm.WorkRecordVM;
import com.vivo.system.entity.VivoDingConf;
import com.vivo.system.service.VivoDingConfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 读取数据库中的钉钉待办信息
 */
@Component
public class TaskUpdDingWR {

    @Autowired
    private DingWorkRecordService workRecordService;

    @Autowired
    private VivoDingConfService dingConfService;

    @Autowired
    private DingUserInfoService dingUserInfoService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private DingConfUtil dingConfUtil;

    public void SyncData() {
        SyncNeedAddWR();

        SyncNeedCancelWR();
    }

    /**
     * 同步需要添加待办事项的列表
     * 判断条件为： 待办状态为待发送
     */
    private void SyncNeedAddWR() {
        System.out.println("开始处理钉钉待办消息： 处理待发送消息...");

        // 获取待发送列表
        List<DingWorkRecord> workRecordList = workRecordService.getByStatu("待发送");

        for (DingWorkRecord workRecord: workRecordList) {
            String status = "待办中";
            String remarks = "";

            do {
                if (workRecord.getEmpId() == null || StringUtils.isBlank(workRecord.getEmpId())) {
                    status = "发送失败";
                    remarks = "员工编号不能为空！";
                    continue;
                }

                if (StringUtils.isBlank(workRecord.getTitle()) || StringUtils.isBlank(workRecord.getUrl()) ||
                        StringUtils.isBlank(workRecord.getFormTitle1()) || StringUtils.isBlank(workRecord.getFormCont1())){
                    status = "发送失败";
                    remarks = "参数不全，缺少title,url,formTitle,formCont等参数！";
                    continue;
                }

                User user =  systemService.getUserByEmpId(workRecord.getEmpId());

                System.out.println("正在发送[" + user.getName() + "]的待办任务：" + workRecord.getTitle());

                if (user == null) {
                    status = "发送失败";
                    remarks = "找不到对应的用户信息";
                    continue;
                }

                DingUserInfo dingUserInfo = dingUserInfoService.getByMobile(user.getLoginName());
                if (dingUserInfo == null) {
                    status = "发送失败";
                    remarks = "找不到对应的用户钉钉登陆信息！请提醒其进行钉钉登陆操作！";
                    continue;
                }

                VivoDingConf dingConf = dingConfUtil.getDingConf(user.getCompany().getId());
                if (dingConf == null) {
                    status = "发送失败";
                    remarks = "该二级区域还没有进行钉钉绑定设置，提醒管理员进行相关绑定操作！二级区域：" + user.getCompany().getName();
                    continue;
                }

                workRecord.setComp(user.getCompany());
                workRecord.setDingUserId(dingUserInfo.getDingUserId());
                workRecord.setUser(user);

                WorkRecordVM workRecordVM = new WorkRecordVM();
                workRecordVM.setPhone(user.getLoginName());
                workRecordVM.setEmpId(workRecord.getEmpId());
                workRecordVM.setTitle(workRecord.getTitle());
                workRecordVM.setUrl(workRecord.getUrl());
                workRecordVM.setFormTitle(workRecord.getFormTitle1());
                workRecordVM.setFormCont(workRecord.getFormCont1());
                workRecordVM.setAccessToken(dingConf.getAccessToken());
                workRecordVM.setDingUserId(dingUserInfo.getDingUserId());

                OapiWorkrecordAddResponse rsp = null;
                try {
                    rsp = SendDingDingMsgUtil.sendWorkRecord(workRecordVM);

                    if (rsp.getErrcode() != 0L) {
                        status = "发送失败";
                        remarks = rsp.getErrmsg();
                        continue;
                    }
                } catch (Exception e) {
                    status = "发送失败";
                    remarks = e.getMessage();
                    continue;
                }

                workRecord.setRecordId(rsp.getRecordId());
            } while (false);

            workRecord.setStatus(status);
            workRecord.setRemarks(remarks);
            try {
                workRecordService.save(workRecord);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        System.out.println("开始处理钉钉待办消息： 待发送消息处理完成。");
    }

    /**
     * 同步需要更新待办的列表
     * 判断条件为： 待办状态为待取消
     */
    private void SyncNeedCancelWR() {
        System.out.println("开始处理钉钉待办消息： 处理待同步消息...");

        // 获取待取消列表
        List<DingWorkRecord> workRecordList = workRecordService.getByStatu("待同步");
        for (DingWorkRecord workRecord: workRecordList) {
            String status = "已完成";
            String remarks = "";
            do {
                if (workRecord.getRecordId() == null || StringUtils.isBlank(workRecord.getRecordId())) {
                    status = "更新失败";
                    remarks = "参数不全，待办编号不能为空！";
                    continue;
                }

                VivoDingConf dingConf = dingConfService.getByComp(workRecord.getComp().getId());
                if (dingConf == null) {
                    status = "更新失败";
                    remarks = "找不到对应二级的配置信息！" + workRecord.getComp().getName();
                    continue;
                }

                System.out.println("正在完成[" + workRecord.getUser().getName() + "]的待办任务：" + workRecord.getTitle());

                try {
                    OapiWorkrecordUpdateResponse rsp = SendDingDingMsgUtil.updWorkRecord(dingConf.getAccessToken(), workRecord.getDingUserId(), workRecord.getRecordId());
                    if (rsp.getErrcode() != 0) {
                        status = "更新失败";
                        remarks = rsp.getErrmsg();
                        continue;
                    }
                } catch (Exception e) {
                    status = "更新失败";
                    remarks = e.getMessage();
                }
            } while (false);

            workRecord.setStatus(status);
            workRecord.setRemarks(remarks);
            try {
                workRecordService.save(workRecord);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        System.out.println("开始处理钉钉待办消息： 待同步消息处理完成。");
    }
}
